import type { MockMethod } from 'vite-plugin-mock'
import Mock from 'mockjs'
import { UserRoleTableRows } from './user_role'
import { Role, RoleTableRows } from './role'
import { RolePermissionTableRows } from './role_permission'
import { Permission, PermissionTableRows } from './permission'
const Random = Mock.Random
const mock = Mock.mock

export interface User {
  id: string
  username: string
  password: string
  address: string
  phone: string
  realname: string
  status: string
  avatar: string
  email: string
  roles: Role[]
  permissions: Permission[]
}

// const getUser = (): User => ({
//   id: Random.guid(),
//   address: Random.county(true),
//   phone: `1${Random.string('number', 10)}`,
//   realname: Random.cname(),
//   email: Random.email(),
//   ...mock({
//     username: Random.string('lower', Random.integer(6, 18)),
//     avatar() {
//       return Random.image('100x100', Random.color(), Random.color(), this.username[0])
//     },
//     status() {
//       const status = ['Active', 'Pending', 'Banned', 'Rejected']
//       return status[Random.integer(0, status.length - 1)]
//     }
//   })
// })

export const UserTableRows: User[] = [
  {
    status: 'active',
    password: '123456',
    phone: `1${Random.string('number', 10)}`,
    realname: Random.cname(),
    email: Random.email(),
    address: Random.county(true),
    ...mock({
      id: '1',
      username: 'root',
      avatar() {
        return Random.image('100x100', Random.color(), Random.color(), this.username[0])
      },
      roles() {
        return UserRoleTableRows.filter((row) => row.user_id === this.id).map((row) =>
          RoleTableRows.find((role) => role.id === row.role_id)
        )
      },
      permissions() {
        const roles = this.roles as Role[]
        const role_ids = roles.map((row) => row.id)
        return RolePermissionTableRows.filter((row) => role_ids.includes(row.role_id)).map((row) =>
          PermissionTableRows.find((permission) => permission.id === row.permission_id)
        )
      }
    })
  }
].concat(
  new Array(101).fill(null).map(() => ({
    id: Random.guid(),
    address: Random.county(true),
    phone: `1${Random.string('number', 10)}`,
    realname: Random.cname(),
    email: Random.email(),
    ...mock({
      username: Random.string('lower', Random.integer(6, 18)),
      avatar() {
        return Random.image('100x100', Random.color(), Random.color(), this.username[0])
      },
      status() {
        const status = ['active', 'pending', 'banned', 'rejected']
        return status[Random.integer(0, status.length - 1)]
      },
      roles() {
        return UserRoleTableRows.filter((row) => row.user_id === this.id).map((row) =>
          RoleTableRows.find((role) => role.id === row.role_id)
        )
      },
      permissions() {
        const roles = this.roles as Role[]
        const role_ids = roles.map((row) => row.id)
        return RolePermissionTableRows.filter((row) => role_ids.includes(row.role_id)).map((row) =>
          PermissionTableRows.find((permission) => permission.id === row.permission_id)
        )
      }
    })
  }))
)

const userList = ({ query }) => {
  const { page = 1, size = 20, status = 'all', roles = '', keyword = '' } = query
  const p = +page
  const s = +size
  let data = UserTableRows
  if (status !== 'all') {
    data = data.filter((row) => row.status === status)
  }
  if (roles) {
    const rs = roles.split(',') as string[]
    data = data.filter((row) => row.roles.find((role) => rs.includes(role.id)))
  }
  if (keyword) {
    data = data.filter(
      (row) =>
        row.username.indexOf(keyword) > -1 ||
        row.email.indexOf(keyword) > -1 ||
        row.address.indexOf(keyword) > -1 ||
        row.phone.indexOf(keyword) > -1 ||
        row.realname.indexOf(keyword) > -1
    )
  }
  return {
    total: data.length,
    page: p,
    size: s,
    data: data.slice((p - 1) * s, p * s)
  }
}

export default [
  {
    url: '/mock-api/ui/user/list',
    method: 'get',
    response({ query }) {
      const { total, page, size, data } = userList({ query })
      return {
        status: true,
        message: 'success',
        code: 0,
        data: {
          id: 'user-list',
          tableKey: 'id',
          table: {
            data,
            attrs: {
              stripe: true,
              border: true,
              'default-sort': {
                prop: 'date',
                order: 'ascending'
              }
            }
          },
          columns: [
            {
              id: 'avatar',
              'slot-default': 'picture',
              attrs: {
                label: '头像',
                prop: 'avatar'
              }
            },
            {
              id: 'username',
              attrs: {
                label: '用户名',
                prop: 'username',
                'show-overflow-tooltip': true,
                width: '100px'
              }
            },
            {
              id: 'phone',
              attrs: {
                label: '手机号',
                prop: 'phone',
                width: '120px'
              }
            },
            {
              id: 'email',
              attrs: {
                label: '邮箱',
                prop: 'email',
                'show-overflow-tooltip': true,
                width: '100px'
              }
            },
            {
              id: 'realname',
              attrs: {
                label: '姓名',
                prop: 'realname'
              }
            },
            {
              id: 'status',
              'slot-default': 'status',
              status: {
                all: ['所有', 'info'],
                active: ['激活', 'success'],
                pending: ['待定', 'primary'],
                banned: ['禁止', 'warning'],
                rejected: ['拒绝', 'danger']
              },
              attrs: {
                label: '状态',
                prop: 'status'
              }
            },
            {
              id: 'address',
              attrs: {
                label: '地址',
                prop: 'address',
                'show-overflow-tooltip': true,
                width: '200px'
              }
            }
          ],
          pagination: {
            'current-page': page,
            'page-size': size,
            total: total,
            attrs: {
              background: true,
              layout: 'total, sizes, prev, pager, next, jumper'
            }
          },
          filter: {
            id: 'user-list-search-form',
            submitText: '查询',
            submitStyle: {
              'justify-self': 'end'
            },
            resetText: '重置',
            form: {
              action: '/mock-api/user/list',
              method: 'get',
              model: {
                keyword: '',
                status: 'all'
              },
              attrs: {
                inline: true,
                style: {
                  'grid-template-areas': `
                            "status keyword . form-submit"
                        `
                }
              }
            },
            fields: [
              {
                'field-type': 'input',
                'field-label': '',
                id: 'keyword',
                model: 'keyword',
                attrs: {
                  placeholder: '请输入关键字搜索'
                },
                'grid-area': 'keyword'
              },
              {
                'field-type': 'select',
                options: [
                  {
                    label: '所有',
                    value: 'all'
                  },
                  {
                    label: '激活',
                    value: 'active'
                  },
                  {
                    label: '待定',
                    value: 'pending'
                  },
                  {
                    label: '禁止',
                    value: 'banned'
                  }
                ],
                'field-label': '',
                id: 'status',
                model: 'status',
                attrs: {
                  placeholder: '用户状态'
                },
                'grid-area': 'status'
              }
            ]
          },
          detail: {
            form: {
              id: 'user-detail-form',
              submitText: '详情',
              form: {
                action: '/mock-api/user/$1',
                method: 'get',
                model: {}
              },
              fields: []
            },
            info: {
              id: 'user-detail',
              detail: {
                model: {},
                'descriptions-attrs': {
                  border: true,
                  column: 2
                },
                attrs: {}
              },
              fields: [
                {
                  id: 'username',
                  'field-type': 'text',
                  'field-label': '用户名',
                  model: 'username',
                  'descriptions-item-attrs': {},
                  attrs: {}
                },
                {
                  id: 'avatar',
                  'field-type': 'avatar',
                  'field-label': '头像',
                  model: 'avatar',
                  'descriptions-item-attrs': {},
                  attrs: {}
                },

                {
                  id: 'realname',
                  'field-type': 'text',
                  'field-label': '真实姓名',
                  model: 'realname',
                  'descriptions-item-attrs': {},
                  attrs: {}
                },
                {
                  id: 'phone',
                  'field-type': 'text',
                  'field-label': '手机号码',
                  model: 'phone',
                  'descriptions-item-attrs': {},
                  attrs: {}
                },
                {
                  id: 'email',
                  'field-type': 'text',
                  'field-label': '邮箱',
                  model: 'email',
                  'descriptions-item-attrs': {
                    span: 2
                  },
                  attrs: {}
                },
                {
                  id: 'address',
                  'field-type': 'text',
                  'field-label': '地址',
                  model: 'address',
                  'descriptions-item-attrs': {
                    span: 2
                  },
                  attrs: {}
                }
              ]
            }
          },
          add: {
            id: 'user-add-form',
            submitText: '新增',
            submitStyle: {
              'justify-self': 'end'
            },
            form: {
              action: '/mock-api/user',
              method: 'post',
              model: {},
              attrs: {
                'label-width': 80,
                style: {
                  gap: '10px',
                  'grid-template-areas': `
                            "username password"
                            "email realname"
                            "roles permissions"
                            "avatar avatar"
                            ". form-submit"
                        `
                }
              }
            },
            fields: [
              {
                'field-type': 'input',
                'field-label': '用户名',
                id: 'username',
                model: 'username',
                attrs: {},
                'grid-area': 'username'
              },
              {
                'field-type': 'input',
                'field-label': '密码',
                id: 'password',
                model: 'password',
                attrs: {
                  type: 'password'
                },
                'grid-area': 'password'
              },
              {
                'field-type': 'input',
                'field-label': '邮箱',
                id: 'email',
                model: 'email',
                attrs: {},
                'grid-area': 'email'
              },
              {
                'field-type': 'input',
                'field-label': '真实姓名',
                id: 'realname',
                model: 'realname',
                attrs: {},
                'grid-area': 'realname'
              },
              {
                'field-type': 'object-select',
                'field-label': '角色',
                id: 'roles',
                model: 'roles',
                attrs: {
                  optionLabel: 'remark',
                  optionValue: 'id',
                  options: RoleTableRows,
                  selectAttrs: {
                    multiple: true
                  }
                },
                'grid-area': 'roles'
              },
              {
                'field-type': 'object-select',
                'field-label': '权限',
                id: 'permissions',
                model: 'permissions',
                attrs: {
                  optionLabel: 'remark',
                  optionValue: 'id',
                  options: PermissionTableRows,
                  selectAttrs: {
                    multiple: true
                  }
                },
                'grid-area': 'permissions'
              },
              {
                'field-type': 'image-upload',
                'field-label': '头像',
                id: 'avatar',
                model: 'avatar',
                attrs: {
                  action: '/mock-api/file/image'
                },
                'grid-area': 'avatar'
              }
            ]
          },
          edit: {
            id: 'user-edit-form',
            submitText: '编辑',
            submitStyle: {
              'justify-self': 'end'
            },
            form: {
              action: '/mock-api/user/$1',
              method: 'put',
              model: {},
              attrs: {
                'label-width': 80,
                style: {
                  gap: '10px',
                  'grid-template-areas': `
                            "username password"
                            "email realname"
                            "roles permissions"
                            "avatar avatar"
                            ". form-submit"
                        `
                }
              }
            },
            fields: [
              {
                'field-type': 'input',
                'field-label': '用户名',
                id: 'username',
                model: 'username',
                attrs: {
                  disabled: true
                },
                'grid-area': 'username'
              },
              {
                'field-type': 'input',
                'field-label': '密码',
                id: 'password',
                model: 'password',
                attrs: {
                  type: 'password',
                  disabled: true
                },
                'grid-area': 'password'
              },
              {
                'field-type': 'input',
                'field-label': '邮箱',
                id: 'email',
                model: 'email',
                attrs: {},
                'grid-area': 'email'
              },
              {
                'field-type': 'input',
                'field-label': '真实姓名',
                id: 'realname',
                model: 'realname',
                attrs: {},
                'grid-area': 'realname'
              },
              {
                'field-type': 'object-select',
                'field-label': '角色',
                id: 'roles',
                model: 'roles',
                attrs: {
                  optionLabel: 'remark',
                  optionValue: 'id',
                  options: RoleTableRows,
                  selectAttrs: {
                    multiple: true
                  }
                },
                'grid-area': 'roles'
              },
              {
                'field-type': 'object-select',
                'field-label': '权限',
                id: 'permissions',
                model: 'permissions',
                attrs: {
                  optionLabel: 'remark',
                  optionValue: 'id',
                  options: PermissionTableRows,
                  selectAttrs: {
                    multiple: true
                  }
                },
                'grid-area': 'permissions'
              },
              {
                'field-type': 'image-upload',
                'field-label': '头像',
                id: 'avatar',
                model: 'avatar',
                attrs: {
                  action: '/mock-api/file/image'
                },
                'grid-area': 'avatar'
              }
            ]
          },
          remove: {
            id: 'user-remove-form',
            submitText: '删除',
            form: {
              action: '/mock-api/user/$1',
              method: 'delete',
              model: {}
            },
            fields: []
          }
        }
      }
    }
  },
  {
    url: '/mock-api/user/list',
    method: 'get',
    response({ query }) {
      const { total, page, size, data } = userList({ query })
      return {
        status: true,
        message: 'success',
        code: 0,
        data: {
          total,
          page,
          size,
          data
        }
      }
    }
  },
  {
    url: '/mock-api/user/:id',
    method: 'delete',
    response() {
      return {
        status: true,
        message: 'success',
        code: 0,
        data: 1
      }
    }
  },
  {
    url: '/mock-api/user',
    method: 'post',
    response({ body }) {
      body.id = Random.guid()
      return {
        status: true,
        message: 'success',
        code: 0,
        data: body
      }
    }
  },
  {
    url: '/mock-api/user/:id',
    method: 'put',
    response({ body }) {
      return {
        status: true,
        message: 'success',
        code: 0,
        data: body
      }
    }
  },
  {
    url: '/mock-api/user/:id',
    method: 'get',
    response({ url }) {
      const id = url.replace('/mock-api/user/', '')
      console.log(id)
      return {
        status: true,
        message: 'success',
        code: 0,
        data: UserTableRows[0]
      }
    }
  }
] as MockMethod[]
